package com.lib.framework.widget.dialog

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.databinding.DataBindingUtil
import com.lib.framework.R
import com.lib.framework.databinding.WidgetLoadingDialogBinding

/**
 * Loading 对话框
 *
 * @author keanbin
 */
class LoadingDialog(context: Context) : BaseDialog(context, R.style.defaultDialogTheme02) {

    private val mHandler = Handler(Looper.getMainLooper())

    /**
     * 是否需要显示
     */
    private var mIsNeedShow = false

    /**
     * 延时显示时间，单位毫秒
     */
    private var mShowDelayTime = 0L

    private var mDataBinding: WidgetLoadingDialogBinding? = null

    init {
        initView()

        setCanceledOnTouchOutside(false)
        setCancelable(false)
    }

    private fun initView() {
        mDataBinding = DataBindingUtil.inflate(layoutInflater, R.layout.widget_loading_dialog, null, false)
        mDataBinding?.let { dataBinding ->
            setContentView(dataBinding.root)
        }
    }

    /**
     * 设置提示文本
     */
    fun setText(text: String?) {
        if (text == null) {
            mDataBinding?.tvText?.visibility = View.GONE
        } else {
            mDataBinding?.tvText?.text = text
            mDataBinding?.tvText?.visibility = View.VISIBLE
        }
    }

    override fun show() {
        mIsNeedShow = true
        if (mShowDelayTime <= 0) {
            realShow()
            return
        }

        mHandler.postDelayed(mShowRunnable, mShowDelayTime)
    }

    private val mShowRunnable = Runnable { realShow() }

    override fun cancel() {
        mHandler.removeCallbacks(mShowRunnable)
        mIsNeedShow = false
        super.cancel()
    }

    override fun dismiss() {
        mHandler.removeCallbacks(mShowRunnable)
        mIsNeedShow = false
        super.dismiss()
    }

    /**
     * 设置 延时显示时间，单位毫秒
     */
    fun setShowDelayTime(delayMillis: Long) {
        mShowDelayTime = delayMillis
    }

    /**
     * 真正的显示
     */
    private fun realShow() {
        if (!mIsNeedShow) return

        mIsNeedShow = false
        super.show()
    }
}